<?php
namespace App\Service;

use App\Model\BmrUserModel;

class LoginService {
    protected $phone;
    protected $name;
    protected $errors;
    protected $userModel;
    protected $user;

    public function __construct($params)
    {
        $this->userModel = new BmrUserModel();
        $this->initParams($params);
    }

    /**初始化参数
     * @param $params
     */
    protected function initParams($params) {
        $this->phone = $params['phone'] ?? '';
        $this->name = $params['name'] ?? '';
    }

    /**检查参数
     * @return bool
     */
    protected function checkParam() {
        $errors = [];
        $phonePattern = '/^1([38]\d|5[0-35-9]|7[3678])\d{8}$/';
        if (!preg_match($phonePattern, $this->phone)) {
            $errors[] = '手机号码格式不正确';
        }

        return true;
    }

    /**获取错误原因
     * @return mixed
     */
    public function getErrors() {
        return $this->errors;
    }

    public function getUser() {
        return $this->user;
    }

    //执行登录动作
    public function action()
    {
        //验证参数错误
        $checkResult = $this->checkParam();
        if ($checkResult !== true) {
            $this->errors = $checkResult;
            return false;
        }
        $this->user = $this->userModel->findPhone($this->phone);
        if (!$this->user) {
            //自动注册一个用户
            if (!$this->register()) {
                $this->errors[] = '自动注册失败';
                return false;
            }
            $this->user = $this->userModel->findPhone($this->phone);
        }

        return true;
    }

    //注册动作
    protected function register()
    {
        $this->userModel->name = trim($this->name);
        $this->userModel->phone = trim($this->phone);
        return $this->userModel->save();
    }
}